//
//  dataHelper.m
//  AngelaBaby
//
//  Created by lanou3g on 15/10/13.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "dataHelper.h"
#import "MBProgressHUD.h"
#import "CategoryModel.h"
#import "ListModel.h"
#import "DetailModel.h"
#import "HomeModel.h"

@interface dataHelper ()

@property(nonatomic,strong)MBProgressHUD *hud;

@end


static dataHelper *datahelper =nil;
@implementation dataHelper
+(instancetype)shareDataHelper{
    if(datahelper ==nil){
        datahelper = [[dataHelper alloc]init];
    }
    return datahelper;
}

//下载封装
-(void)downloadFileWithOption:(NSDictionary *)paramDic withURL:(NSString *)requestURL savePath:(NSString *)savedPath downloadSuccess:(void(^)(AFHTTPRequestOperation *operation,id responseObject))success downloadFailure:(void(^)(AFHTTPRequestOperation *operation,NSError *error))failure progress:(void(^)(float progress))progress{
    
    AFHTTPRequestSerializer *serializer =[AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request =[serializer requestWithMethod:@"GET" URLString:requestURL parameters:paramDic error:nil];
    AFHTTPRequestOperation *operation =[[AFHTTPRequestOperation alloc]initWithRequest:request];
    
    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:savedPath append:NO]];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        float p =(float)totalBytesRead/totalBytesExpectedToRead;
        progress(p);
//        NSLog(@"download:%f",(float)totalBytesRead/totalBytesExpectedToRead);
    }];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        success(operation,responseObject);
        NSLog(@"下载成功");
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        failure(operation,error);
        NSLog(@"下载失败");
    }];
    [operation start];
}







//解析封装
-(void)getDataWithUrl:(NSString *)url dic:(NSDictionary *)dic model:(id)model returnArray:(void(^)(NSMutableArray *arra))valueArray{
    NSMutableArray *array=[NSMutableArray array];
    [self getDataWithUrl:url dic:dic success:^(id operation) {
        
         NSDictionary *dictionary = (NSDictionary *)operation;
        
        if ([model isKindOfClass:[ListModel class]]) {
            NSArray *arr=dictionary[@"list"];
           
            for (ListModel *temp in arr) {
                ListModel *mo= [[ListModel alloc]init];
                [mo setValuesForKeysWithDictionary:(NSDictionary *)temp];
                [array addObject:mo];
                
            }
        } else if ([model isKindOfClass:[DetailModel class]]){
            NSArray *arr=dictionary[@"tracks"][@"list"];
           
            for (DetailModel *temp in arr) {
                DetailModel *mo= [[DetailModel alloc]init];
                [mo setValuesForKeysWithDictionary:(NSDictionary *)temp];
                [array addObject:mo];
            }
        }else if ([model isKindOfClass:[AlbumModel class]]){
            NSDictionary *dic=dictionary[@"album"];
                AlbumModel *mo= [[AlbumModel alloc]init];
                [mo setValuesForKeysWithDictionary:(NSDictionary *)dic];
                [array addObject:mo];
        }else if ([model isKindOfClass:[HomeModel class]]){
            NSArray *arr=dictionary[@"list"];
            for (NSDictionary *dic in arr) {
                HomeModel *mo= [[HomeModel alloc]init];
                [mo setValuesForKeysWithDictionary:(NSDictionary *)dic];
                [array addObject:mo];
            }
        }
       
        valueArray(array);
    } fail:^(NSError *error) {
        
    }];
}






//get请求: url为网址,dic为{id:"###"},operation和error分别为传回去的成功和失败的信息
-(void)getDataWithUrl:(NSString *)url dic:(NSDictionary *)dic success:(void(^)(id operation))success fail:(void(^)(NSError * error))fail{
//        AFNetworkReachabilityManager *manager=[AFNetworkReachabilityManager sharedManager];
//    //没网的情况
//    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
//        return;
//    }else{
        //有网的情况
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[[dataHelper alloc]init].hud show:YES];
            AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
            [manager GET:url parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
                [[[dataHelper alloc]init].hud hide:YES];
                [[[dataHelper alloc]init].hud removeFromSuperview];
                
                success(responseObject);
            } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError *  _Nonnull error)
             {
                 [[[dataHelper alloc]init].hud hide:YES];
                 [[[dataHelper alloc]init].hud removeFromSuperview];
                 fail(error);
             }];
//        });
        
//    }
//    [manager startMonitoring];
   }




#pragma mark 菊花懒加载
-(MBProgressHUD *)hud{
    if (!_hud) {
        _hud = [[MBProgressHUD alloc]initWithView:[[UIApplication sharedApplication].delegate window]];
        _hud.labelText =@"加载中";
        _hud.detailsLabelText =@"字标题";
        _hud.labelColor =[UIColor grayColor];
    }

    return _hud;
}



@end
